// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.tcmdb.rest.service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.query.Criteria;

import de.servicezombie.cxf.WebserviceTemplate;
import de.servicezombie.cxf.WebserviceTemplateFactory;
import de.servicezombie.lang.text.OrderedSublistRequest;
import de.servicezombie.tcmdb.dao.mongo.TestcaseDefinitionDao;
import de.servicezombie.tcmdb.rest.RestTransformerSupport;
import de.servicezombie.tcmdb.rest.SameInstanceTransformer;
import de.servicezombie.tcmdb.rest.vo.WsApplication;
import de.servicezombie.tcmdb.rest.vo.WsListResult;
import de.servicezombie.tcmdb.rest.vo.WsTestcaseDefinition;

public class ApplicationServiceRestImpl implements ApplicationService {

	private static final Logger log = LoggerFactory.getLogger(ApplicationServiceRestImpl.class);
	
	private TestcaseDefinitionDao testcaseDefinitionDao;
	
	public void setTestcaseDefinitionDao(TestcaseDefinitionDao testcaseDefinitionDao) {
		this.testcaseDefinitionDao = testcaseDefinitionDao;
	}
		
	/**
	 * <em>current implementation might be slow if work with 
	 * thousands of testcases.<em>
	 * 
	 * {@inheritDoc}
	 */
	@Override
	public void getActiveApplications(String sublistRequest) {
		if (log.isDebugEnabled()) {
			log.debug("getActiveApplications: >>");
		}
		
		/* parse input at once to find invalid input earlier */
		OrderedSublistRequest request = OrderedSublistRequest.valueOf(sublistRequest);				
		Collection<WsApplication> result = buildRequestedApplicationSubset(request);
		/* ChKa TODO add support for orderByClauses (Jan 25, 2012) */		
		
		RestTransformerSupport restTransformerSupport = new RestTransformerSupport();
		WsListResult<WsApplication> wsResult = restTransformerSupport.toWsListResult(
				result, new SameInstanceTransformer<WsApplication>());

		WebserviceTemplate template = new WebserviceTemplateFactory().build();
		template.getWebserviceResponse().setBody(wsResult);
		
		if (log.isDebugEnabled()) {
			log.debug("getActiveApplications: << " + wsResult);
		}
	}

	private Collection<WsApplication> buildRequestedApplicationSubset(OrderedSublistRequest request) {
		
		List<WsTestcaseDefinition> definitions = testcaseDefinitionDao.findByCriteria(
				new Criteria("inactive").is(false)
			);
		
		Collection<WsApplication> result = new HashSet<WsApplication>();
		for(WsTestcaseDefinition d : definitions) {
			result.addAll(d.getApplications());
		}
		result = request.buildSublist(result);
		return result;
	}


}
